package com.xxx.reggie.controller;

import com.xxx.reggie.common.R;
import com.xxx.reggie.entity.Employee;
import com.xxx.reggie.entity.Page;
import com.xxx.reggie.service.EmployeeService;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RequestMapping("/employee")
@RestController
public class EmployeeController {


    //注入业务EmployeeService
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //调用业务获取登入结果
        R<Employee> login = employeeService.login(employee);

        //判断是否登入成功,如果成功,将数据写入到session
        if (login.getCode()==1){
            session.setAttribute("employee",login.getData());
        }
        return login;
    }

    @RequestMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success(null);
    }


    @RequestMapping(method = RequestMethod.POST)
    public R<String> save(@RequestBody Employee employee,HttpSession session){

        //从登入数据获取当前登入操作人
        Employee loginEmployee = (Employee) session.getAttribute("employee");

        //完善数据(创建人id与修改人id)
        employee.setCreateUser(loginEmployee.getId());
        employee.setUpdateUser(loginEmployee.getId());

        //调用业务添加员工
        employeeService.save(employee);

        //返回成功数据
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Employee>> findByName(Integer page, Integer pageSize, String name){

        //调用业务获取分页数据
        Page<Employee> pageObj = employeeService.findByName(page, pageSize, name);

        //封装结果并返回
        return R.success(pageObj);

    }


    @RequestMapping(method = RequestMethod.PUT)
    public R<String> update(@RequestBody Employee employee,HttpSession sessions){

        //获取当前登入操作员工信息对象
        Employee loginEmployee = (Employee) sessions.getAttribute("employee");

        //完善Employee给修改人赋值
        employee.setUpdateUser(loginEmployee.getId());

        //调用业务修改
        employeeService.update(employee);

        //封装结果返回
        return R.success("修改成功");
    }

    @RequestMapping(method = RequestMethod.GET,value = "/{id}")
    public R<Employee> findById(@PathVariable long id){

        //调用业务根据id获取员工对象
        Employee employee = employeeService.findById(id);

        //封装数据返回
        return R.success(employee);

    }
}
